package com.tgl.vegetables.plug.hema;

import android.accessibilityservice.AccessibilityService;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.NonNull;

import com.tgl.vegetables.plug.R;
import com.tgl.vegetables.plug.service.BaseAccessibilityService;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class HemaAccessibilityService extends BaseAccessibilityService {

    private static final String TAG = "HemaAccessibilityService";

    private static final List<String> ALL_TIMES1 = new ArrayList<String>() {
        {
            add("今日 08:00-08:30送达");
            add("今日 08:30-09:00送达");
            add("今日 09:00-09:30送达");
            add("今日 09:30-10:00送达");
            add("今日 10:00-10:30送达");
            add("今日 10:30-11:00送达");
            add("今日 11:00-11:30送达");
        }
    };

    private static final List<String> ALL_TIMES2 = new ArrayList<String>() {
        {
            add("今日 14:00-14:30送达");
            add("今日 14:30-15:00送达");
            add("今日 15:00-15:30送达");
            add("今日 15:30-16:00送达");
            add("今日 16:00-16:30送达");
            add("今日 16:30-17:00送达");
            add("今日 17:00-17:30送达");
        }
    };

    private List<String> mTimes = new ArrayList<>();
    private int mTotalSubmitCount = 0;

    private int mPreWindowType = WINDOW_HOME;

    public HemaAccessibilityService() {
        super();
        mHandler.removeMessages(MSG_CLICK_EVENT);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityService context, AccessibilityEvent accessibilityEvent) {
        Log.e(TAG, "accessibilityEvent = " + accessibilityEvent.toString());
        super.onAccessibilityEvent(context, accessibilityEvent);
        int type = accessibilityEvent.getEventType();
        String className = accessibilityEvent.getClassName().toString();
        if (type == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            switch (className) {
                case "com.wudaokou.hippo.launcher.splash.SplashActivity":
                case "com.wudaokou.hippo.cart.container.CartMainActivity":
                    mShopCarSelected = false;
                    processHomeActivity(accessibilityEvent);
                    break;
                case "com.wudaokou.hippo.buy3.ultronage.HMUltronTradeActivity":
                    processOrderActivity(accessibilityEvent);
                    break;
                case "android.support.v7.app.AlertDialog":
                    processOrderDialog(accessibilityEvent);
                    break;
                default:
                    break;
            }
        } else if (type == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
            if (isSelectedTimePage(accessibilityEvent)) {
                processTimeSelectView(accessibilityEvent);
            }
        }
    }

    private boolean processOrderDialog(AccessibilityEvent accessibilityEvent) {
        mPreWindowType = mCurrentWindow;
        mCurrentWindow = WINDOW_DIALOG;
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());

        /*AccessibilityNodeInfo root = accessibilityEvent.getSource();
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "确定", 0);
        if (nodeInfo != null) {
            if (nodeInfo.isClickable()) {
                performClick(nodeInfo, 0);
            } else {
                performClick(nodeInfo, 1);
            }
        }*/
        return true;
    }

    private void processHomeActivity(AccessibilityEvent accessibilityEvent) {
        mRootAccessibilityNodeInfo = accessibilityEvent.getSource();
        if (!mShopCarSelected) {
            mShopCarSelected = doSelectShopCar(mRootAccessibilityNodeInfo);
        }
        mTotalSubmitCount = 0;
        mCurrentWindow = WINDOW_HOME;
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
    }

    private void processOrderActivity(AccessibilityEvent accessibilityEvent) {
        mRootAccessibilityNodeInfo = accessibilityEvent.getSource();
        mCurrentWindow = WINDOW_ORDER;
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
    }

    private void processTimeSelectView(AccessibilityEvent accessibilityEvent) {
        mHandler.removeMessages(MSG_CLICK_EVENT);
        mCurrentWindow = WINDOW_SELECT_TIME;
        mRootAccessibilityNodeInfo = accessibilityEvent.getSource();
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, DURATION);
    }

    private boolean isSelectedTimePage(AccessibilityEvent accessibilityEvent) {
        try {
            if (mCurrentWindow != WINDOW_ORDER) {
                return false;
            }
            AccessibilityNodeInfo root = accessibilityEvent.getSource();
            AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "选择时间", 0);
            AccessibilityNodeInfo nodeInfo1 = findAccessibilityNodeInfo(root, "确认", 0);
            if (nodeInfo1 == null) {
                nodeInfo1 = findAccessibilityNodeInfoViewId(root, "com.wudaokou.hippo:id/picker_confirm", 0);
            }
            if (nodeInfo != null && nodeInfo1 != null && nodeInfo1.isVisibleToUser()) {
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }

    }

    private boolean doSelectShopCar(AccessibilityNodeInfo nodeInfo) {
        nodeInfo = findAccessibilityNodeInfo(nodeInfo, "购物车", 0);
        if (nodeInfo != null) {
            performClick(nodeInfo, 0);
            return "购物车，已选中".equals(nodeInfo.getContentDescription()) || nodeInfo.isSelected();
        }
        return false;
    }

    @Override
    public void onInterrupt() {

    }

    private void onClickCalc() {
        if (!mShopCarSelected) {
            mShopCarSelected = doSelectShopCar(mAccessibilityService.getRootInActiveWindow());
        }
        AccessibilityNodeInfo root = mAccessibilityService.getRootInActiveWindow();
        if(dismissDialog(root)){
            return;
        }
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "提交订单", 0);
        if (nodeInfo != null) {
            mCurrentWindow = WINDOW_ORDER;
            return;
        }

        nodeInfo = findAccessibilityNodeInfoViewId(root, "com.wudaokou.hippo:id/button_cart_charge", 0);
        if (nodeInfo != null) {
            performClick(nodeInfo, 0);
        }
    }

    private boolean dismissDialog(AccessibilityNodeInfo root){
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "确定", 0);
        if (nodeInfo != null) {
            if (nodeInfo.isClickable()) {
                performClick(nodeInfo, 0);
            } else {
                performClick(nodeInfo, 1);
            }
            return true;
        }
        return false;
    }

    private boolean dismissDialogV2(AccessibilityNodeInfo root){
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "确定", 0);
        if (nodeInfo != null) {
            autoClickPoint(mScreenWidth * 4 / 5 - 10, mScreenHeight - 30);
            return true;
        }
        return false;
    }

    private AccessibilityNodeInfo getSelectTimeNodeInfo(AccessibilityNodeInfo root) {
        try {
            AccessibilityNodeInfo nodeInfo = root.findAccessibilityNodeInfosByText("包裹1").get(0).getParent().getChild(3);
            if(nodeInfo.isClickable()){
                return nodeInfo;
            }
            return null;
        }catch (Exception e){
            return null;
        }
    }

    private boolean backPressed() {
        AccessibilityNodeInfo root = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo title = findAccessibilityNodeInfoViewId(root, "com.wudaokou.hippo:id/title", 0);
        if (title == null || title.getChildCount() < 1) {
            return false;
        }
        AccessibilityNodeInfo back = title.getChild(0);
        if (back.isClickable()) {
            performClick(back, 0);
            return true;
        }
        return false;
    }

    private void onClickOrder() {
        AccessibilityNodeInfo root = mAccessibilityService.getRootInActiveWindow();
        if (root == null) {
            root = mRootAccessibilityNodeInfo;
        }
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfoViewId(root, "com.wudaokou.hippo:id/button_cart_charge", 0);
        if(nodeInfo != null){
            mCurrentWindow = WINDOW_HOME;
            return;
        }

        //root.findAccessibilityNodeInfosByText("包裹1").get(0).getParent().getChild(3)

        if(dismissDialogV2(root)){
            return;
        }

        nodeInfo = findAccessibilityNodeInfo(root, "非常抱歉，当前商品运力不足(063)", 0);
        if (nodeInfo == null) {
            nodeInfo = findAccessibilityNodeInfo(root, "￥0.00", 0);
        }
        if (nodeInfo != null) {
            if(!backPressed()){
                mAccessibilityService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
            }
        } else {
            nodeInfo = findAccessibilityNodeInfo(root, "提交订单", 0);
            if (nodeInfo != null) {

                if (mTotalSubmitCount > 5) {
                    AccessibilityNodeInfo selectTime = getSelectTimeNodeInfo(root);
                    if (selectTime != null && selectTime.isClickable()) {
                        performClick(selectTime,0);
                        return;
                    }
                }

                if (nodeInfo.isClickable() && nodeInfo.isEnabled()) {
                    if (!performClick(nodeInfo, 0)) {
                        mAccessibilityService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                    }
                    mTotalSubmitCount++;
                } else {
                    backPressed();
                }
            }
        }

    }

    @Override
    protected long getDuration() {
        return 50;
    }

    private AccessibilityNodeInfo findValidTime() {
        AccessibilityNodeInfo root = mRootAccessibilityNodeInfo;
        if (root == null) {
            root = mAccessibilityService.getRootInActiveWindow();
        }
        Random random = new Random();
        while (mTimes.size() > 0) {
            int index = random.nextInt(mTimes.size());
            String time = mTimes.remove(index);
            AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, time, 0);
            if (nodeInfo == null) {
                continue;
            }
            AccessibilityNodeInfo parent = nodeInfo.getParent();
            AccessibilityNodeInfo child = parent.getChild(1);
            if (!TextUtils.isEmpty(child.getText()) && !" ".equals(child.getText()) && child.isVisibleToUser()) {
                continue;
            }
            return parent;
        }
        return null;
    }

    private void onClickTimeSelect() {
        mCurrentWindow = WINDOW_ORDER;
        AccessibilityNodeInfo root = mRootAccessibilityNodeInfo;
        if (root == null) {
            root = mAccessibilityService.getRootInActiveWindow();
        }
        mTotalSubmitCount = 0;
        if (mTimes.isEmpty()) {
            Calendar calendar = Calendar.getInstance();
            if (calendar.get(Calendar.HOUR_OF_DAY) > 11) {
                mTimes.addAll(ALL_TIMES2);
            } else {
                mTimes.addAll(ALL_TIMES1);
            }
        }

        AccessibilityNodeInfo nodeInfo = findValidTime();
        if (nodeInfo != null) {
            Rect rect = new Rect();
            nodeInfo.getBoundsInScreen(rect);
            autoClickPoint(rect.left + 10, rect.top + 10);
        }

        nodeInfo = findAccessibilityNodeInfo(root, "确认", 0);
        if (nodeInfo == null) {
            nodeInfo = findAccessibilityNodeInfoViewId(root, "com.wudaokou.hippo:id/picker_confirm", 0);
        }
        if (nodeInfo != null) {
            performClick(nodeInfo, 0);
        }
    }

    private void onClickDismissDialog(){
        mCurrentWindow = mPreWindowType;
        autoClickPoint(mScreenWidth * 4 / 5 - 10, mScreenHeight - 30);
    }

    private void onClick() {
        switch (mCurrentWindow) {
            case WINDOW_HOME:
                onClickCalc();
                break;
            case WINDOW_ORDER:
                onClickOrder();
                break;
            case WINDOW_SELECT_TIME:
                onClickTimeSelect();
                break;
            case WINDOW_DIALOG:
                onClickDismissDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean handleMessage(@NonNull Message message) {
        switch (message.what) {
            case MSG_CLICK_EVENT:
                onClick();
                mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, DURATION);
                break;
            default:
                break;
        }
        return false;
    }
}
